using System.IO;
using Android.App;
using Android.OS;
using Android.Provider;
using Android.Widget;
using Newtonsoft.Json;

namespace MapDrawer
{
    public class RenameDialog : DialogFragment
    {
        private readonly PathTracker _pt;

        public RenameDialog(PathTracker pt)
        {
            _pt = pt;
        }

        public EditText Tv { get; set; }

        public override Dialog OnCreateDialog(Bundle savedInstanceState)
        {
            base.OnCreateDialog(savedInstanceState);
            Tv = new EditText(_pt);
      
            var builder =
                new AlertDialog.Builder(_pt).SetMessage("Ancien nom: " + _pt.SelectedFile.ToString())
                    .SetPositiveButton("Modifier", (sender, args) =>
                    {
                        try
                        {
                            if (Tv.Text != "")
                            {
                                File.Move("/storage/sdcard0/" + _pt.SelectedFile, "/storage/sdcard0/" + Tv.Text);
                                _pt.Files[_pt.Files.IndexOf(_pt.SelectedFile)] = Tv.Text;
                                System.IO.File.WriteAllText("/storage/sdcard0/pathList.json", JsonConvert.SerializeObject(_pt.Files));
                                _pt.InitSpinner();
                                Dismiss();
                            }
                            else
                            {
                                Toast.MakeText(_pt, "Le nom de fichier n'est pas valide.", ToastLength.Short).Show();
                            }
                        }
                        catch (IOException ex)
                        {
                            Toast.MakeText(_pt,"Impossible de renommer le fichier.",ToastLength.Short).Show();
                        }
                    })
                    .SetTitle("Renommer un trajet")
                    .SetNeutralButton("Annuler", (sender, args) => Dismiss())
                    .SetView(Tv);
            return builder.Create();
        }
    }
}